local LuaMongo = _G.lua_mongo
local Config = require("Config")
local Log = require("common.Log")
local Util = require("common.Util")
local Log = require("common.Log") 
local ObjHuman = require("core.ObjHuman")
local BuyLogic = require("topup.BuyLogic")
local RoleDBLogic = require("role.RoleDBLogic")
local ReportManager = require("platform.ReportManager")
local Lang = require("common.Lang")
local Broadcast = require("broadcast.Broadcast")
local BuyExcel = require("excel.buy").buy
local Msg = require("core.Msg")

--[[
result:
1：充值成功
2：用户不存在
3：验证错误
4：订单号已存在
5：参数有错
6：参数不全
7：请求过时
8：其他原因
--]]

DAY_PAY_NONAGE_1 = 50
DAY_PAY_NONAGE_2 = 100
MONTH_PAY_NONAGE_1 = 200
MONTH_PAY_NONAGE_2 = 400

DELIVER_CODE_HIS = DELIVER_CODE_HIS or {}
function deliver(oJsonInput,ret)
	oJsonInput.type = tonumber(oJsonInput.type)
	oJsonInput.id = tonumber(oJsonInput.id)
	oJsonInput.cnt = tonumber(oJsonInput.cnt)
	oJsonInput.money = tonumber(oJsonInput.money)
	ret.account = oJsonInput.account
	ret.order = oJsonInput.order
	ret.type = oJsonInput.type
	ret.id = oJsonInput.id
	ret.cnt = oJsonInput.cnt
	ret.money = oJsonInput.money
	ret.region = oJsonInput.region
	ret.err = ""
	if not (ret.account and ret.order and ret.type and ret.id and ret.cnt and ret.region) then
		ret.result = 6
		ret.err = "param empty"
		return
	end
	
	if DELIVER_CODE_HIS[oJsonInput.order] then
		ret.result = 4
		ret.err = "order double"
		return
	end
	DELIVER_CODE_HIS[oJsonInput.order] = os.time()

	local human = ObjHuman.onlineAccount[ret.account]
	local online = true
	if not human then
		local humanDb = RoleDBLogic.loadRole(ret.account)
		human = {}
		human.db = humanDb
		online = false
		if not humanDb then
			ret.result = 2
			ret.err = "account not exist"
			return
		end
	end
	
	if not BuyLogic.checkBuy(human,ret) then
		return
	end
	
	oJsonInput.cmd = "deliver"
	if online and human.db.middleFlag == nil then
		if Config.IS_DEBUG then
			BuyLogic.buy(human,ret.id)
		else
			local pcallRet, pcallErr = pcall(BuyLogic.buy, human,ret.id)
			if not pcallRet then
				Log.write(Log.LOGID_ERR_PCALL, "BuyLogic.buy err=" .. human.db.account, pcallErr)
				ret.result = -1
				ret.err = pcallErr
				return Broadcast.sendErr(human, "BuyLogic.buy "..Lang.PCALL_ERR) 
			end
		end
	else
		human.db.buyOrder = human.db.buyOrder or {}
		human.db.buyOrder[#human.db.buyOrder + 1] = Util.copyTable(oJsonInput)
	end
	
	RoleDBLogic.saveRole(human.db)
	ret.result = 1
	Log.write(Log.LOGID_OSS_DELIVER, human.db._id, human.db.account, human.db.name, human.db.lv,oJsonInput.order,oJsonInput.money,oJsonInput.type,oJsonInput.id,oJsonInput.cnt,online and 1 or 0,oJsonInput.region)	
end


--[[
1：充值成功
2：用户不存在
3：验证错误
4：订单号已存在
5：充值元宝数量有错
6：参数不全
7：请求过时
8：参数错误
-1：未知错误
--]]
CHARGE_CODE_HIS = CHARGE_CODE_HIS or {}
function charge(oJsonInput,ret)
	oJsonInput.gold = tonumber(oJsonInput.gold)
	oJsonInput.money = tonumber(oJsonInput.money)
	oJsonInput.buyID = tonumber(oJsonInput.buyID)
	ret.account = oJsonInput.account
	ret.order = oJsonInput.order
	ret.gold = oJsonInput.gold
	ret.money = oJsonInput.money
	ret.region = oJsonInput.region
	ret.appid = oJsonInput.appid or ""
	ret.err = ""
	if not (ret.account and ret.order and ret.gold and ret.money and ret.region) then
		ret.result = 6
		ret.err = "param empty"
		return
	end
	
	if CHARGE_CODE_HIS[oJsonInput.order] then
		ret.result = 4
		ret.err = "order double"
		return
	end

	local human = ObjHuman.onlineAccount[ret.account]
	local online = true
	if not human then
		local humanDb = RoleDBLogic.loadRole(oJsonInput.account)
		human = {}
		human.db = humanDb
		online = false
		if not humanDb then
			ret.result = 2
			ret.err = "account not exist"
			return
		end
	end

    local topupMoney = 0
	local buyConf = oJsonInput.buyID and BuyExcel[oJsonInput.buyID]

    if oJsonInput.buyID == 3 then
        if human.db.fundFlag ~= nil then
            ret.result = 5
		    ret.err = "funds cannot be bought multiple times"
		    return
        end
    end
    if not BuyLogic.isArgOK(human,oJsonInput.buyID,ret.region,ret.money) then
		ret.result = 5
		ret.err = "money not fix config"
		return
	end

	CHARGE_CODE_HIS[oJsonInput.order] = os.time()
	oJsonInput.cmd = "charge"
	
    local price = 0
    if ret.money ~= 0 then
        price = ret.money
    else
        price = buyConf["CN"][1]
    end
    oJsonInput.topupMoney = price
	
	human.db.buyHis = human.db.buyHis or {}
	human.db.buyHis[#human.db.buyHis + 1] = {buyID = oJsonInput.buyID or 0,money = ret.money,gold = ret.gold,upTime = os.time()}
	
	if online and human.db.middleFlag == nil then
		if Config.IS_DEBUG then
			BuyLogic.charge(human,oJsonInput)
		else
			local pcallRet, pcallErr = pcall(BuyLogic.charge, human,oJsonInput)
			if not pcallRet then
				Log.write(Log.LOGID_ERR_PCALL, "BuyLogic.charge err=" .. human.db.account, pcallErr)
				ret.result = -1
				ret.err = pcallErr
				return Broadcast.sendErr(human, "BuyLogic.charge "..Lang.PCALL_ERR) 
			end
		end
	else
		human.db.buyOrder = human.db.buyOrder or {}
		human.db.buyOrder[#human.db.buyOrder + 1] = Util.copyTable(oJsonInput)
    end
	
    RoleDBLogic.saveRole(human.db)
    ret.result = 1
    if ret.order ~= 'transaction_id1' then
        Log.write(Log.LOGID_OSS_PAY, human.db._id, human.db.account, human.db.name, human.db.lv,ret.order,oJsonInput.buyID or 0,oJsonInput.amt or ret.money,ret.gold,online and 1 or 0,ret.region)
    end

    local orderExt = {['orderID'] = oJsonInput.order, ['amount'] = oJsonInput.money}
    if oJsonInput.ext then
        local extData = Json.Decode(oJsonInput.ext)
        orderExt.OrderNO = extData.OrderNO
        orderExt.GoodsCode = extData.GoodsCode
    end
    
    orderExt.PayPurchaseType = buyConf.cmd == "topup" and 0 or 3
    orderExt.ItemCode = oJsonInput.buyID
    orderExt.ItemName = buyConf.name
    orderExt.Amount = 1
    orderExt.CurrencyCode = "KRW"
    orderExt.TotalPrice = oJsonInput.money
    orderExt.PayToolCode = 1
    orderExt.ReceiveMemberID = oJsonInput.account
    orderExt.Balance = human.db.zuanshi
    orderExt.PayResultType = 1
    orderExt.PayResultMessage = "success"

    ReportManager.charge(human, orderExt)
end